<template>
  <div class='body_message_detail'>
    <!-- 这里是真实发生 用户 交流 的地方 【上下结构：上：交流信息；下：发送信息】-->
    
    <div class="title_box">
      <div><span>{{you_data.nickName}}</span></div>
    </div>
    <div class="message_detail_box">
      <div class='message_detail_list' ref="detailList">
        <el-scrollbar ref="message_detail_scroll">
          <div class='get_more' 
            v-show="this.pageData.totalPage !== 0 && this.pageData.currentPage != this.pageData.totalPage">
            <span @click="getMore(you_data.dialId)" >加载更多</span>
          </div>
          <mdItem v-for="(item, index) in message_detail" :key='index'
            :detail_item="item" :you_data="you_data" ></mdItem>
        </el-scrollbar>
      </div>
      <!-- <div>
        <el-button @click="showScrollTop">滚动条信息</el-button>
      </div> -->
    </div>
    
    <div class="send_box">
      <div></div>
      <div>
        <el-input
          type="textarea"
          
          placeholder="请输入内容..."
          resize='none'
          v-model="textarea">
        </el-input>
      </div>
      <div>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>
    
  </div>
</template>

<script>
import mdItem from './message-detail-item';
export default {
  components: {
    mdItem,
  },
  // activated() {
  //   this.websocket.onmessage=function(event){
  //     console.log("ws收到数据", event.data);
  //   }
  // },
  mounted(){
    // 聊天内容 视图的高度
    // this.scroll_view_base = this.$refs['detailList'].offsetHeight
    // console.log("scroll_view_base",this.scroll_view_base)
  },
  props:{
    you_data: Object,
    new_message: Object,
    websocket: WebSocket,
    changeNewContent: Function,
  },
  computed:{  },
  watch:{
    // 初次 获取数据
    you_data:{
      handler: function(newValue){
        console.log("detial:you_data的值发生修改", newValue)
        // 在这里产生第一次数据的获取、初始化数据
        // this.scroll_view = this.scroll_view_base;
        // console.log("scroll_view",this.scroll_view)
        // this.setScrollTop();
        this.detailId = 0
        this.message_detail=[]
        this.scrollSign.firstSign = true;
        if(newValue.dialId !== 0){
          this.getMore(newValue.dialId)
        }
      },
      // immediate: true,
    },
    // 收到数据 
    new_message:{ 
      handler: function(newValue){
        this.recvMessage(newValue);
      }
    },
    // 信息数据发生修改
    message_detail: function(newValue, oldValue){
      this.messageDetailListChange()
      /*
      this.$nextTick(()=>{
      })
      */
    }
  },
  data() {
    return {
      scrollSign:{
        firstSign: true,
        recvSign: false, // 收到消息，滚动条不动
      },
      textarea: '',
      dial_id: 0, // 这个数据在 you_data 中有
      detailId: 0,  // 查询历史记录时需要
      pageData:{
        "limit":7,
        "totalPage":2,
        "currentPage":1
      },
      scroll_view: 0,
      scroll_view_base: 0,
      // my_data:{
      //   nickName:'老张',
      //   portrait:'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      // },
      // 维护着 当前用户和其他用户的对话信息
      message_detail:[
      /*
      {
        detialId: 0,
        isMine : 0,
        content: 'nihao',
        createTime: '',
        readStatus: 0,
      },{
        detialId: 1,
        isMine : 1,
        content: 'niyehao',
        createTime: '',
        readStatus: 0,

      },{
        detialId: 2,
        isMine : 0,
        content: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxnnnnnnx',
        createTime: '',
        readStatus: 0,
      },{
        detialId: 4,
        isMine : 1,
        content: '1234567890x1234567890x1234567890x1234567890x1234567890',
        createTime: '',
        readStatus: 0,

      },
      */
      ],
      

    }
  },
  methods: {
    // 打印 滚动条信息
    showScrollTop(){
        console.log(
          "top",this.$refs['message_detail_scroll'].wrap.scrollTop, 
          "height",this.$refs['message_detail_scroll'].wrap.scrollHeight,
          "view_height",this.$refs['detailList'].offsetHeight,
        )
        // this.$refs['message_detail_scroll'].wrap.scrollTop = 80;
    },
    
    // 发送消息 【发送】
    sendMessage(){
      if(this.you_data.dialId === 0){
        this.$message({
          type:'error',
          message:"请先选择一个用户",
        })
        return;
      }
      this.scroll_view = this.scroll_view_base;
      console.log('我发送数据：',this.textarea, this.you_data, this.currentUser.user);
      var data = {
        "dialogId": this.you_data.dialId,
        "sendUid": this.currentUser.user.uid,
        "recvUid": this.you_data.uid,
        "content": this.textarea,
      }
      this.addMessageToList({"isMine": 1,"content": this.textarea, })
      this.changeNewContent(this.you_data.dialId, this.textarea);
      var jsonStr = JSON.stringify(data);
      this.websocket.send(jsonStr);
      this.textarea = ""
    },
    // 增加到 列表 中
    addMessageToList(message){
      this.message_detail.push(message);
    },
    // 收到消息 【收到】
    recvMessage(message){
      if(message.dialogId == this.you_data.dialId){
          // this.scroll_view = this.calcScrollView();
          this.scrollSign.recvSign = true;
          this.addMessageToList({isMine: 0,content: message.content, })
          this.$notify.info({
            title: '消息',
            message: '收到一条新消息',
            duration: 1500,
          });
        }
    },

    // 获取更多 对话的信息 【获取更多】
    getMore(dialId){
      // 计算 滚动条的 temp
      this.scroll_view = this.calcScrollView();

      console.log("获取更多和["+this.you_data.nickName+"]的对话")
      // return;
      var data = {
        page: '1',
        limit: ''+this.pageData.limit,
        sidx: 'create_time',
        order: 'desc'
      }
      this.$http1({
        url: this.$http.adornUrl(`/user/dialog/detail/page/${dialId}/${this.detailId}`),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "获取对话记录!",
        });
        // console.log("list",typeof(data.page.list), data.page.list);
        if(data.page.list.length === 0){
          this.pageData.currentPage = data.page.currPage;
          this.pageData.totalPage = data.page.totalPage;
          return;
        }
        this.detailId = data.page.list[0].detailId;
        this.message_detail = [...data.page.list, ...this.message_detail ];
        this.pageData.currentPage = data.page.currPage;
        this.pageData.totalPage = data.page.totalPage;
        console.log("具体信息", data.page.list , "pageData", this.pageData);
      });
    },

    // 信息详情数据变动，调整滚动条
    messageDetailListChange(){
      this.$nextTick(()=>{
        // 无论是 if 还是 else ，都是要保证当前界面不变
        if(this.scrollSign.firstSign){ // 初次查看消息
          this.setScrollBottom();
          this.scrollSign.firstSign = false;
          return;
        }
        if(this.scrollSign.recvSign){ // 收到新消息，下方数据增多，top无需调整
          this.scrollSign.recvSign = false;
          return;
        }
        // 从后端获取数据，上方数据增多，top需要调整
        // 发送数据
        this.setScrollTop() // 设置滚动条的位置
      })
    },

    // 计算 ScrollView
    calcScrollView(){
      // this.$nextTick(()=>{
        return this.$refs['message_detail_scroll'].wrap.scrollHeight - 
            this.$refs['message_detail_scroll'].wrap.scrollTop;
      // })
      
    },
    // 滚动条 置低
    setScrollBottom(){
      this.scroll_view_base = this.$refs['detailList'].offsetHeight;
      this.scroll_view = this.scroll_view_base;
      this.setScrollTop();
    },
    // 设置 滚动条的位置
    setScrollTop(){
      this.$refs['message_detail_scroll'].wrap.scrollTop = this.$refs['message_detail_scroll'].wrap.scrollHeight - this.scroll_view;
    }
  },
}
</script>

<style>
  .body_message_detail{
    position: absolute;
    width: 100%;
    height: 100%;
  }

  .title_box{
    position: absolute;
    width: 100%;
    height: 36px;
    background: #eee;
    border-bottom: 1px solid #e9eaec;
  }
  .title_box > div{
    position: relative;
    padding: 10px 0px;
    text-align: center;
  }


  .message_detail_box{
    position: absolute;
    width: 100%;

    top: 36px;
    bottom: 162px;
    /* height: 200px; */

    background:#f4f5f7;
  }
  .message_detail_list{
    margin: 0px 20px;
    height: 100%; /** 显示的高度 */ /** 修改这里时，别忘了修改属性 scroll_view */
    
  }
  /** 
    对滚动条的理解：
      一个是要展示的内容，一个是可供展示的界面大小
      前者与实际的数据相关，我们无法控制
      后者与 界面 和 滚动条 相关，二者共同作用 于 最终显示界面的大小
      【其实核心还是与 滚动条.el-scrollbar 的大小相关】
  */


  .message_detail_list .el-scrollbar {
    height: 100%; /** 显示的高度 */
  }
  .message_detail_list .el-scrollbar__wrap {
    overflow-x: hidden; /* 隐藏水平滚动条，但是还占位置 */
  }


  .send_box{
    position: absolute;
    width: 100%;
    height: 162px;
    bottom: 0px;
    border-top: 1px solid #d8d8d8;
    background: #f4f5f7;
  }
  .send_box div:nth-child(1){
    /* height: 48px; */
    height: 20px;
  }
  .send_box div:nth-child(2){
    /* height: 60px; */
    height: 88px;
  }
  .send_box .el-textarea{
    /* height: 88px; */
    /* width: 100%; */
    /* margin: 0 auto; */
    
  }
  .send_box textarea{
    height: 88px;
    border:0;
    border-radius:0px;
    /* 背景颜色 */
    background: #f4f5f7;
  }
  .send_box div:nth-child(3){
    height: 46px;
  }
  .send_box div:nth-child(3) button{
    top: 5px;
    position: relative;
    float: right;
    margin-right: 20px;
  }



  .get_more{
    color: white;
    text-align: center;
    margin-top: 15px;
    margin-bottom: 15px;
  }
  .get_more span{
    background-color: #cecece;
    padding: 5px 10px;
    cursor: pointer;
  }
</style>